package com.bubbleby.social.launch.server;


import com.bubbleby.social.launch.client.RegisterService;
import com.bubbleby.social.launch.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

/**
 * The server side implementation of the RPC service. Adds email, hashes and ip address to the Datastore.
 */
@SuppressWarnings("serial")
public class RegisterServiceImpl extends RemoteServiceServlet implements RegisterService {
	
	
	public String registerServer(String email, String referrerToken, String myToken) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidEmail(email)) {
			throw new IllegalArgumentException(I18nAppEngineConstants.errorEmailFormat());
		}
	
		
		ObjectifyService.register(Registration.class);
		Registration reg = new Registration(email,referrerToken,myToken, getThreadLocalRequest().getRemoteAddr()); 
		Objectify ofy = ObjectifyService.begin(); 
		
		try {
			Registration user = ofy.get(Registration.class, email);
			return user.myToken;
		} catch (NotFoundException e) {
			ofy.put(reg);
		}
			
		return reg.myToken;
	}

}
